//
//  File.swift
//
//
//  Created by didi on 2022/9/14.
//

import Fluent
import Molecular
import MolecularObjects
import MolecularUserObjects
import Vapor

struct UserAccountTokenAuthenticator: AsyncBearerAuthenticator {
    func authenticate(bearer: BearerAuthorization, for request: Request) async throws {
        guard let token = try await UserTokenModel.query(on: request.db).filter(\.$value == bearer.token).first() else { return }

        let now = Date()
        guard token.expiration > now else { return }
        guard let user = try await request.user.account.repository.get(token.accountId) else { return }

        let roles = try await request.user.role.repository.findWithPermissions(user.uuid, request)
        let isRoot = !roles.filter { $0.key == User.Role.Keys.Root }.isEmpty
        request.auth.login(MUser(id: user.uuid, level: isRoot ? .root : .authenticated, roles: roles))
        token.expiration = now.addingTimeInterval(86400 * 7)
        try await token.update(on: request.db)
    }
}
